package cn.tansanqinger.linked;

import java.util.Arrays;
import java.util.Iterator;

interface IList<E>{
    boolean add(E e);
    Iterator<E> iterator();
}
class ArrayListImpl<E> implements IList<E>{
    private Object elementData[];//数组
    private int listLength = -1;//数组中数据长度
    private final int DEFAULTLENGTH = 10;
    //无参构造
    public ArrayListImpl(){
        this(0);
    }
    public ArrayListImpl(int size){
        if(size>=0){
            this.elementData = new Object[size];
        } else {
            throw new IllegalArgumentException("你输入的数据错误"+size);
        }
    }
    private Object[] newCapacity(E e){
        if(this.elementData.length==0){
            this.elementData = new Object[this.DEFAULTLENGTH];//初始化默认值
        } else {
            int oldCapacity = this.elementData.length;//获取数据原始长度
            int newCapacity = oldCapacity>>1;//增加的长度
            this.elementData = Arrays.copyOf(elementData,oldCapacity+newCapacity);//扩容
        }
        this.elementData[++this.listLength] = e;//添加数据
        return this.elementData;
    }
    @Override
    public boolean add(E e) {
        if(this.elementData.length==this.listLength+1){//数组已经满载了，需要开辟新的长度
            newCapacity(e);
        } else {
            this.elementData[++this.listLength] = e;//添加数据
        }
        return true;
    }

    @Override
    public Iterator<E> iterator() {
        return new Ite();
    }
    private class Ite implements Iterator{
        int len=-1;
        @Override
        public boolean hasNext() {
            return this.len != listLength;
        }
        @Override
        public Object next() {
            if(len<listLength){
                return elementData[++len];
            }
            return null;
        }
    }
}
public class SimulateArrayList {
    public static void main(String[] args) {
        IList<String> list = new ArrayListImpl<>();
        list.add("A");
        list.add("B");
        list.add("C");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
